package under.wsl.cacheador;

/**
 * @author alexandre.araujo
 */
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import under.wsl.request.RequestService;

public class Cache {	
	String urlCache = new String();
	
	public Cache(){
		this.urlCache="C:/sistemas/temp";
		try { 
        	this.urlCache = this.getClass().getResource("/").getFile()+"cache_tmp";       	
            File dir = new File(this.urlCache);            	
			if(!dir.exists()){
				dir.mkdirs(); 
			};                         
         } catch (Exception ex) {
            System.out.println("erro ao procurar path:"+ex.getMessage().toString());                             
         }
	}
	public void setUrl(String urlCache){
		this.urlCache=urlCache;
	}	
	public String getUrl(){
		return this.urlCache;
	}	
	public boolean checkExist(RequestService servico){
		File f = new File(this.urlCache+"/"+servico.getServico()+"."+servico.getMetodo()+".json");
		return f.isFile();
	}
	public StringBuffer getCache(RequestService servico){
		StringBuffer acu = new StringBuffer("");
		try {
		    File f = new File(this.urlCache+"/"+servico.getServico()+"."+servico.getMetodo()+".json");
		    FileReader fr = new FileReader(f);  
	        BufferedReader br = new BufferedReader(fr);       
	        String s;	       
			while((s=br.readLine())!=null){          
				 acu.append(s);
			} 
			fr.close();
			br.close();
		} catch (Exception e) {
			System.out.println("erro no file:"+e.getMessage().toString());
		} 		
		return acu;		
	}
	
    public void clear(String servico[]){
    	int tmS = servico.length;
    	for(int i=0;i<tmS;i++){    	
			File f = new File(this.urlCache+"/"+servico[i]+".json");
			if(f.exists()){
				f.delete();
			};
    	}
    }
    public void save(RequestService servico){
        BufferedWriter br = null;  
        try {
        	if(!(servico.getTipo().toLowerCase().equals("list") && servico.getRs().equals("[]"))){
        		br = new BufferedWriter(new FileWriter(new File(this.urlCache+"/"+servico.getServico()+"."+servico.getMetodo()+".json")));
        		br.write(servico.getRs()+""); 
        		br.close();
        	}
        } catch (Exception ex) {
            System.out.println("erro ao criar o arquivo:"+ex.getMessage().toString());
        }
    }
}
